<template>
    <div class="select-wrap c-clearfix">
        <span class="select-label">{{ label }}</span>
        <div class="select-group" :style="{width: width}">
            <a href="javascript:" class="select-value" :class="{cue: show}" :style="{width: width}" @click="toggle">
                <span v-if="!multiple">{{ selectItem ? selectItem[textKey] : placeholder }}</span>
                <span v-else>{{ isCheckAll ? '全部' : (selectItemsText ? selectItemsText : placeholder) }}</span>
            </a>
            <div v-show="show" class="select-list-wrap" :style="{width: width}">
                <div v-if="hasSearch" class="search-wrap">
                    <input type="text" class="c-form-control search" placeholder="搜索" ref="searchInput" @input="search" @click.stop>
                </div>
                <ul>
                    <li v-if="multiple && hasCheckAll">
                        <a href="javascript:" @click.stop="checkAll()" class="c-checkbox"
                           :class="{selected: isCheckAll, checked: isCheckAll}">全部</a>
                    </li>
                    <li v-for="(item, index) in (searchType!='self' ? selectListSelf : filterList)">
                        <a href="javascript:" @click.stop="select(item)"
                           :class="{special: item.special, selected: item.selected, 'c-checkbox': multiple, checked: multiple&&item.selected}">{{ item[textKey] }}</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: 'selectGroup',
        data(){
            return {
                show: false,
                selectListSelf: [],
                filterList: [], // 搜索后过滤后的list
                timing: null,   // 搜索延迟
            }
        },
        computed: {
            selectItem(){
                for(let i = 0; i < this.selectListSelf.length; i++){
                    if(this.selectListSelf[i].selected){
                        return this.selectListSelf[i];
                    }
                }
                return null
            },
            selectItems(){
                let items = [];
                for(let i = 0; i < this.selectListSelf.length; i++){
                    if(this.selectListSelf[i].selected){
                        items.push(this.selectListSelf[i]);
                    }
                }
                return items;
            },
            selectItemsText(){
                return this.selectItems.map(
                    item => item[this.textKey]
                ).join(',');
            },
            isCheckAll(){
                if(this.selectListSelf.length>0){
                    for(let i = 0; i < this.selectListSelf.length; i++){
                        if(! this.selectListSelf[i].selected){
                            return false;
                        }
                    }
                    return true;
                }else{
                    return false
                }
            },
        },
        created(){
            // 解除数据绑定，组件单元独立
            if(this.voidItem){
                this.selectListSelf = JSON.parse( JSON.stringify([this.voidItem].concat(this.selectList)) );
            }else{
                this.selectListSelf = JSON.parse( JSON.stringify(this.selectList) );
            }

            // 初始化选中的值
            if(this.initValue){
                this.selectOneItem(this.initValue.key, this.initValue.value);
            }

            // 更新搜索的列表
            if(this.hasSearch && this.searchType=='self'){
                this.filterList = this.selectListSelf;
            }
        },
        watch: {
            show(val){
                if(val){
                    this.$root.$el.addEventListener('click', this.hide);
                }else{
                    this.$root.$el.removeEventListener('click', this.hide);
                }
            },
            selectList(list){
                // 解除数据绑定，组件单元独立
                if(this.voidItem){
                    this.selectListSelf = JSON.parse( JSON.stringify([this.voidItem].concat(list)) );
                }else{
                    this.selectListSelf = JSON.parse( JSON.stringify(list) );
                }

                // 更新搜索的列表
                if(this.hasSearch && this.searchType=='self'){
                    this.filterList = this.selectListSelf;
                }
            },
        },
        methods: {
            checkAll(){
                if(this.isCheckAll){
                    this.selectListSelf.forEach(
                        item => {
                            this.$set(item, 'selected', false);
                        }
                    );
                }else{
                    this.selectListSelf.forEach(
                        item => {
                            this.$set(item, 'selected', true);
                        }
                    );
                }
            },
            select(item){
                let list = this.selectListSelf;
                if(!this.multiple){
                    for(let i = 0; i < list.length; i++){
                        this.$set(list[i], 'selected', false);
                    }
                }
                if(item.special){
                    this.$emit('select-special', item);
                }else{
                    if(this.multiple){
                        this.$set(item, 'selected', !item.selected);
                    }else{
                        this.show = false;
                        this.$set(item, 'selected', true);
                    }
                    this.$emit('select', item, this.$el);
                }

                if(this.hasSearch && this.searchType=='event'){
                    this.$refs.searchInput.value = item[this.textKey];
                }
            },

            // 清除选择的项目(供父组件调用)
            clearSelect(){
                let list = this.selectListSelf;
                for(let i = 0; i < list.length; i++){
                    this.$set(list[i], 'selected', false);
                }
            },
            // 选中某一项(供父组件调用)
            selectOneItem(key, value){
                this.selectListSelf.forEach(function (item) {
                    this.$set(item, 'selected', item[key] == value);
                }.bind(this));
            },

            // 选中某一项(供父组件调用)
            selectOneItemForBatchChannel(key, value){
                this.selectListSelf.forEach(function (item) {
                    let val = value.replace(/[\$\(\)\*\+\.\[\]\?\/\^\{\}\|]/g, function (word) {
                        return '\\'+word;
                    });
                    let reg = new RegExp("^"+val+"","g");
                    this.$set(item, 'selected', reg.test(item[key]));
                }.bind(this));
            },
            // 切换显示
            toggle(){
                if(! this.show){
                    setTimeout(function () {
                        this.show = !this.show;
                    }.bind(this),0);
                }
            },
            hide(){
                this.show = false;
            },
            search(ev){
                clearTimeout( this.timing );
                // 设置延时，防止频繁发送请求
                this.timing = setTimeout(
                    () => {
                        if(this.searchType == 'event'){
                            this.$emit('search', ev.target.value);
                        }else{
                            this.filterList = [];
                            if(ev.target.value){
                                let reg = "/"+ ev.target.value.replace(/(?=[\(\)\[\]\*\\\!\+\.\^\$\/\|])/g,'\\') +"/g";
                                this.selectListSelf.forEach(
                                    item => {
                                        if(eval(reg).test(item[this.textKey])){
                                            this.filterList.push(item);
                                        }
                                    }
                                );
                            }else{
                                this.filterList = this.selectListSelf;
                            }
                        }
                    }, 350
                );
            },
        },
        props: {
            selectList:  { type: Array },
            textKey:     { type: String, default: 'text' },
            label:       { type: String, default: '' },
            placeholder: { type: String, default: '' },
            width:       { type: String, default: '160px' },
            voidItem:    { default: null },
            initValue:   { default: null }, // key, value
            hasSearch:   { type: Boolean, default: false },
            searchType:  { type: String, default: 'event'}, // event-传递事件至组件（一般服务端搜索），self-自身内部数据搜索
            multiple:    { type: Boolean, default: false},  // 是否多选
            hasCheckAll: { type: Boolean, default: false},  // (多选时)是否有选择全部
        }
    }
</script>

<style lang="scss">
    .select-wrap{
        display: inline-block;text-align: left;
        .select-label{float: left;line-height: 32px;margin-right: 3px;}
        .select-group{float: left;position: relative;border: 1px solid #afb8bd;border-radius: 4px;background: #fff;box-sizing: border-box;}
        a.select-value{position: relative;float: left;color: #293134;line-height: 30px;padding: 0 30px 0 6px;width: 160px;box-sizing: border-box;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}
        .select-value:after{content: '';position: absolute;top: 9px;right: 7px;width: 20px;height: 13px;background-image: url(/static/images/arrow.png);background-position: 20px 0;}
        .select-value.cue:after{background-position: 0 0;}
        .select-list-wrap{
            position: absolute;top: 31px;left: -1px;width: 160px;background: #fff;border-radius: 4px;padding: 4px 0;z-index: 9;border: 1px solid #afb8bd;max-height: 300px;overflow: auto;
            p,a{display: block;padding: 0 6px;line-height: 28px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;color: #293134;}
            a:hover{background: #d9e3ec;}
            a.selected{color: #47bac1;}
            a.special{color: #188bf6;text-align: center;}
        }
        .search-wrap{margin: 2px 6px;}
        .search{width: 100%;}
        .c-checkbox:before{margin-top: 4px;margin-right: 2px;}
    }
</style>
